﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace JXWebApi.Controllers
{
	[ApiController]
	[Route("api/[controller]")]
	public class TestController : ControllerBase
	{
		private static readonly string[] Summaries = new[]
		{
			"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
		};

		private readonly ILogger<TestController> _logger;

		public TestController(ILogger<TestController> logger)
		{
			_logger = logger;
		}

		/// <summary>
		/// 得到天气预报
		/// </summary>
		/// <returns></returns>
		[HttpGet]
		public IEnumerable<WeatherForecast> Get()
		{
			// 获取当前服务地址和端口
			var features = ServiceLocator.ApplicationBuilder.Properties["server.Features"] as FeatureCollection;
			var address = features.Get<IServerAddressesFeature>().Addresses.First();
			_logger.LogInformation($"时间：{DateTime.Now.ToLongTimeString()} 地址：{address} 得到天气预报方法被调用");
			var rng = new Random();
			return Enumerable.Range(1, 5).Select(index => new WeatherForecast
			{
				Date = DateTime.Now.AddDays(index),
				TemperatureC = rng.Next(-20, 55),
				Summary = Summaries[rng.Next(Summaries.Length)] + " 地址："+address
			})
			.ToArray();
		}

		/// <summary>
		/// 得到当前登录用户的信息
		/// </summary>
		/// <returns></returns>
		[HttpGet("GetInfo")]
		[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "SuperAdmin,AdministratorManage")]
		public IActionResult GetInfo()
		{
			return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
		}
	}
}
